<template>
  <div class="content" ref="conversationRef">
    <div class="chat-list">
      <div
        class="chat-item"
        :class="{ client: item.source == SOURCE_VALUE.CLIENT }"
        v-for="(item, i) in chatList"
        :key="i"
      >
        <div class="chat-toolbar" v-if="item.source == SOURCE_VALUE.CLIENT">
          <div class="tools">
            <div class="btn">
              <Icon
                type="md-copy"
                color="#8a95a7"
                size="16"
                @click="onCopy(item.word)"
              />
            </div>
            <div class="btn">
              <Icon type="md-refresh" color="#8a95a7" size="16" />
            </div>
            <div class="btn">
              <Icon type="ios-trash" color="#8a95a7" size="16" />
            </div>
          </div>
          <img
            :src="item.avatar"
            alt="avatar"
            class="avatar"
            v-if="item.avatar"
          />
          <Icon v-else class="user-icon" type="md-person" size="28" />
        </div>
        <div class="chat-toolbar" v-else>
          <img :src="item.avatar || DefaultImg" alt="avatar" class="avatar" />
          <div class="tools">
            <div class="btn">
              <Icon
                type="md-copy"
                color="#8a95a7"
                size="16"
                @click="onCopy(item.word)"
              />
            </div>
            <div class="btn">
              <Icon type="md-refresh" color="#8a95a7" size="16" />
            </div>
            <div class="btn">
              <Icon type="md-create" color="#8a95a7" size="16" />
            </div>
          </div>
        </div>
        <div class="chat-content">
          <div class="word">
            {{ item.word }}
            <div class="suggest-list">
              <div
                class="suggest-item"
                v-for="sug in item.suggest"
                :key="sug.id"
                @click="sendMessage(sug.title)"
              >
                {{ sug.title }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="footer">
    <ul class="file-list">
      <li v-for="(item,index) in files" :key="index">
        <p>{{ item.name }}</p>
        <Icon class="remove-icon" type="md-close-circle" size="18" @click="removeFile(index)" />
      </li>
    </ul>
    <div class="enter">
      <template v-if="showRecorder">
        <p class="word">{{isTranslating? '正在转换文本...' : '我在听，请说...'}}</p>
        <div class="audio-line"></div>
        <div class="time">{{ recorderDuration }}</div>
        <Icon
          title="取消语音输入"
          type="ios-close-circle-outline"
          class="btn"
          color="#fd853a"
          size="28"
          @click="stopRecorder"
        />
        <Icon
          title="提交语音输入 "
          type="ios-checkmark-circle-outline"
          class="btn"
          color="#039855"
          size="28"
          @click="transRecorder"
        />
      </template>
      <template v-else>
        <Upload v-if="agentInfo.isenable" multiple :accept="accept" :before-upload="beforeUpload">
          <Icon  title="上传文件" type="md-attach" size="24" class="pointer" />
        </Upload>
        <Input
          type="textarea"
          v-model="sendWord"
          search
          @keydown="handleKeyDown"
          size="large"
          :border="false"
          :autosize="{ maxRows: 10 }"
          placeholder="输入问题，发送[Enter] / 换行[Shift + Enter]"
        />
        <Icon
          v-if="agentInfo.enablevoiceinput"
          type="ios-mic-outline"
          style="padding: 0 10px; cursor: pointer"
          size="35"
          @click="openRecorder"
          title="语音输入"
        />
        <Button
          type="primary"
          size="large"
          icon="md-send"
          :disabled="!sendWord"
          @click="sendMessage()"
        ></Button>
      </template>
    </div>
  </div>
</template>
<script setup>
import { ref, watch, onBeforeUnmount, nextTick, inject } from 'vue';
import { detailAgent } from '@/api/modules/agent';
import { Message } from 'view-ui-plus';
import moment from 'moment';

import createWebSocket from '@/util/websocket';
import { getFileExtension } from '@/util'
import Recorder from 'js-audio-recorder';

import DefaultImg from '@/assets/imgs/default.png';

const aiid = inject('aiid');

const SOURCE_VALUE = {
  SERVICER: 1,
  CLIENT: 2,
};
const sendWord = ref('');
const chatList = ref([]);
const agentInfo = ref({
  enablevoiceinput: false,
  isenable: false,
});

const socket = createWebSocket('https://demo.zkefu.cn:443/im/ai');
const conversationRef = ref(null);

const word = ref('');
let timer = null;
const showRecorder = ref(false);
const isTranslating = ref(false);
const recorderDuration = ref('00:00');

const recorder = new Recorder({
  sampleBits: 16,
  sampleRate: 16000,
  numChannels: 1,
});

// 开始录音
const openRecorder = () => {
  showRecorder.value = true;
  word.value = '';
  Recorder.getPermission().then(
    () => {
      console.log('开始录音');
      recorder.start(); // 开始录音
      startTransDuration();
    },
    (error) => {
      Message.info('请先允许该网页使用麦克风');
      console.log(`${error.name} : ${error.message}`);
    }
  );
};
// 停止录音
const stopRecorder = () => {
  showRecorder.value = false;
  recorder.stop();
  console.log('停止录音');
  clearInterval(timer);
};

// 转换为文本，需对接后端接口，暂无
const transRecorder = () => {
  isTranslating.value = true;
  recorder.stop();
  clearInterval(timer);
  setTimeout(() => {
    showRecorder.value = false;
  }, 1000)
}

// 转换录音时间
const startTransDuration = () => {
  timer = setInterval(() => {
    const second = recorder.duration.toFixed(0);
    const duration = moment.duration(second, 'seconds');
    const minutes = duration.minutes();
    const seconds = duration.seconds();
    recorderDuration.value = `${minutes > 9 ? minutes : '0' + minutes}:${
      seconds > 9 ? seconds : '0' + seconds
    }`;
  }, 1000);
};

const getAgentDetail = async () => {
  const { data } = await detailAgent({ data: { id: aiid.value } });
  agentInfo.value = data;
};
watch(
  () => aiid.value,
  (newVal) => {
    if (newVal) {
      if (newVal) {
        getAgentDetail();
        socket.on('connect', () => {
          console.log('连接成功');
          // 发送初始化消息
          socket.send('new', {
            orgi: 'ukewo',
            appid: '8da803feb3d55ee739d7400ff098256b',
            aiid: aiid.value,
            userid: '4028cac3614cd2f901614cf8be1f0324',
            user: '4028cac3614cd2f901614cf8be1f0324',
            session: 'de37fc1d0f21494aa690a1e0e854ecb1',
            debug: true,
            osname: '',
            browser: '',
          });
        });
      }
    }
  },
  { immediate: true, deep: true }
);

socket.on('message', (data) => {
  if (data.calltype === 'out') {
    chatList.value.push({
      ...data,
      word: data.message,
    });

    nextTick(() => {
      const el = conversationRef.value;
      el.scrollTop = el.scrollHeight;
    });
  }
});

socket.on('agentstatus', (data) => {
  console.log('agentstatus', data);
});

socket.on('status', (data) => {
  console.log('status', data);
});

const sendMessage = (val) => {
  const searchText = val || sendWord.value;
  if (!searchText) return;

  chatList.value.push({
    word: searchText,
    source: SOURCE_VALUE.CLIENT,
  });

  socket.send({
    appid: '8da803feb3d55ee739d7400ff098256b',
    userid: '4028cac3614cd2f901614cf8be1f0324',
    username: '',
    channel: 'webim',
    debug: true,
    type: 'message',
    contextid: '486b1e7469064f51a88e5f5e335f21ff',
    orgi: 'ukewo',
    message: searchText,
  });

  sendWord.value = '';
};

onBeforeUnmount(() => {
  socket.destory();
});
const onCopy = async (word) => {
  try {
    await navigator.clipboard.writeText(word);
    proxy.$Message.success('已复制');
  } catch (err) {
    proxy.$Message.error(err);
  }
};

const handleKeyDown = (event) => {
  if (!event.shiftKey && event.keyCode == 13) {
    event.cancelBubble = true;
    event.preventDefault();
    event.stopPropagation();
    sendMessage();
  }
};

const accept = '.pdf, .doc, .docx, .txt, .md, .pptx, .ppt, .xls, .xlsx'

const files = ref([])

const beforeUpload = file => {
  if(files.value.length >= 20) {
    Message.warning('最多上传20个文件')
    return false
  }

  const wordType = getFileExtension(file.name)
  if (!accept.includes(wordType)) {
    Message.warning('暂不支持该格式文件上传')
    return false
  }

  const wordMaxSize = 1024 * 1024 * 100


  if(file.size > wordMaxSize) {
    Message.warning('文件大小不能超过100MB')
    return false
  }

  files.value.push(file)
}
const removeFile = index => {
  files.value.splice(index,1)
}
</script>
<style lang="scss" scoped>
.content {
  width: 100%;
  height: calc(100% - 180px);
  overflow-y: auto;
  padding: 10px 20px;
  position: relative;
}
.chat-item {
  width: 100%;
  display: flex;
  flex-direction: column;
  &.client {
    .chat-toolbar,
    .chat-content {
      justify-content: flex-end;
    }
    .chat-content {
      text-align: right;
      .word {
        background-color: #e1eaff;
        border-radius: 8px;
        border-top-right-radius: 0;
      }
    }
  }
  .chat-content {
    display: flex;
    margin-top: 10px;
    justify-content: flex-start;
    text-align: left;
    margin-bottom: 10px;
    .word {
      padding: 10px;
      border-radius: 8px;
      border-top-left-radius: 0;
      background-color: #edeef1;
    }
  }
  .chat-toolbar {
    display: flex;
    align-items: center;
    .tools {
      display: flex;
      align-items: center;
      margin: 0 6px;
      .btn {
        border: 1px solid #dfe2ea;
        padding: 0 4px;
        cursor: pointer;
        &:first-of-type {
          border-top-left-radius: 4px;
          border-bottom-left-radius: 4px;
        }
        &:last-of-type {
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
        }
      }
    }
    .avatar {
      width: 28px;
      height: 28px;
      border-radius: 6px;
    }
  }
}
.pointer {
  cursor: pointer;
}
.footer {
  position: absolute;
  bottom: 20px;
  left: 50%;
  width: calc(100% - 120px);
  transform: translateX(-50%);
  margin: 10px auto;
  padding: 10px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 10px;
  .enter {
    display: flex;
    align-items: center;
    width: 100%;
    /* textarea.ivu-input, textarea, .ivu-input {
      width: 100%;
      height: 40px;
      line-height: 40px;
      max-height: 50vh!important;
    } */
    .word {
      flex: 1;
      color: #666;
    }
    .btn {
      margin-left: 10px;
      cursor: pointer;
    }
  }
}

.audio-line {
  height: 4px;
  width: 100px;
  background: #e1eaff;
  margin-right: 10px;
}
.suggest-item {
  cursor: pointer;
  padding: 6px 0;
  color: #2d8cf0;
}

.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  li {
    width: calc(25% - 10px);
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 8px;
    background-color: #fff;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 10px;
    position: relative;
    
    p {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .remove-icon {
      position: absolute;
      right: -6px;
      top: -6px;
      cursor: pointer;
      opacity: 0;
    }
    &:hover {
      .remove-icon {
        opacity: 1;
      }
    }
    
  }
}
</style>
